// index.js
import {
  get,
  post,
  put
} from '../../utils/request'
import {
  APIS
} from '../../utils/api'
import {
  timestampToTime,
  checkTimeOverlap,
  parseTime
} from '../../utils/util'
// 获取应用实例
const app = getApp()

Page({
  data: {
    currentIndex: 1,
    tabIndex: 0,
    tabFkIndex: 0,
    currentBtn: 0,
    tabs: ['绑定收费规则', '设置收费规则'],
    btns: ['台费设置', '门店信息', '访客列表'],
    showPop: false,
    tableNumbers: [],
    ruleList: [],
    tableIndex: 0,
    startDate: '-',
    endDate: '-',
    rangeStart: '2024-01-01',
    rangeEnd: '2099-01-01',
    tabFks: ['今日', '昨日'],
    currentImg: '',
    shopInfo: {},
    feeForm: [
      ['00:00', '24:00']
    ],
    selectBall: [],
    selectCard: [],
    rsid: ''
  },
  onLoad() {
    let currentIndex = wx.getStorageSync('currentShop');
    this.setData({
      currentIndex
    }, () => {
      this.getRules(currentIndex);
      this.getTables(currentIndex);
      this.setTime('today');
    })
  },
  setTime(mode) {
    let startDate = '';
    let endDate = '';
    let rt = new Date();
    let rangeEnd = `${rt.getFullYear()}-${String(rt.getMonth() + 1).padStart(2, '0')}-${String(rt.getDate()).padStart(2, '0')}`
    let t = new Date(Date.now() - Number(mode === 'yestoday') * 24 * 3600 * 1000);
    startDate = endDate = `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(t.getDate()).padStart(2, '0')}`
    this.setData({
      startDate,
      endDate,
      rangeEnd
    });
  },
  getTables(shop) {
    get(APIS.rulesegment + '/tables', {
      shop
    }).then(res => {
      console.log(res)
      const list = res.data;
      this.setData({
        tableNumbers: list
      });
    })
  },
  getRules(shop) {
    get(APIS.rulesegment, {
      shop
    }).then(res => {
      const ruleList = res.data;
      this.setData({
        ruleList
      });
    })
  },
  handleImg() {
    const that = this;
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: `${APIS.upload}`, //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: 'file',
          success(res) {
            try {
              const data = res.data;
              const info = data && JSON.parse(data);
              const {
                file
              } = info.data;
              that.setData({
                currentImg: file
              });
            } catch (error) {

            }
          }
        })
      }
    })
  },
  tfChecked(params) {
    const {
      name,
      deposit
    } = params;
    let flag = false;
    if (!name || deposit === '' || deposit === undefined) {
      flag = true;
    }
    let {
      feeForm
    } = this.data;
    let len = feeForm.length;
    for (let i = 0; i < len; i++) {
      let n = params['billing_' + i]
      if (n === undefined || n === '') {
        flag = true;
        break;
      }
    }
    if (flag) {
      wx.showToast({
        title: '缺少必填字段',
        icon: 'none'
      })
      return flag;
    }

    let status = checkTimeOverlap(feeForm);
    if (status !== 0) {
      wx.showToast({
        title: status === 1 ? '开始时间不能等于结束时间' : '存在重叠时间',
        icon: 'none'
      })
      return true;
    }
    return false;
  },
  parseTf(params) {
    const {
      name,
      deposit
    } = params;
    let {
      feeForm
    } = this.data;
    return {
      name,
      deposit,
      fee: feeForm.map((val, i) => ({
        range: val,
        fee: params['billing_' + i]
      })).sort((a, b) => parseTime(a.range[0]) - parseTime(b.range[0]))
    }
  },
  formTfSubmit(e) {
    const params = e.detail.value;
    if (this.tfChecked(params)) {
      return;
    }
    let form = this.parseTf(params);
    post(APIS.rulesegment, {
      ...form,
      shop: this.data.currentIndex
    }).then(res => {
      this.setData({
        tabIndex: 0
      });
      this.getRules(this.data.currentIndex);
    })
  },
  formSHSubmit(e) {
    const params = e.detail.value;
    const {
      admin,
      phone
    } = params;
    if (!admin || !phone || !this.data.currentImg) {
      wx.showToast({
        title: '请填写必填项',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    put(`${APIS.shop}/${this.data.currentIndex}`, {
      ...params,
      qrcode: this.data.currentImg
    }).then(res => {
      if (res.code === 0) {
        wx.showToast({
          title: '更新成功',
          icon: 'none',
          duration: 2000
        });
      } else {
        wx.showToast({
          title: '更新失败',
          icon: 'none',
          duration: 2000
        });
      }
    })
  },
  handleShowPop(e) {
    let {
      id
    } = e.currentTarget.dataset;
    this.setData({
      rsid: id,
      showPop: true
    });
  },
  handleStart(e) {
    const startDate = e.detail.value;
    this.setData({
      startDate
    });
  },
  handleEnd(e) {
    const endDate = e.detail.value;
    this.setData({
      endDate
    });
  },
  handleTime(e) {
    let {
      feeForm
    } = this.data;
    let {
      pos,
      type,
      value
    } = e.detail;
    let tmp = feeForm[pos] || ['00:00', '24:00'];
    tmp[type === 'start' ? 0 : 1] = value;
    feeForm[pos] = tmp;
    this.setData({
      feeForm
    })
  },
  handleClose() {
    this.setData({
      showPop: false
    });
  },
  handleJump() {
    wx.navigateTo({
      url: '/pages/distribution/index'
    })
  },
  handleJumpVisitor(e) {
    let {info} = e.currentTarget.dataset
    console.log(info)
    wx.navigateTo({
      url: '/pages/visitor/index?uid=' + info.id
    })
  },
  handleShopIndex(e) {
    const currentIndex = e.detail;
    this.setData({
      currentIndex
    });
    this.getRules(currentIndex);
  },
  handleTableChange(e) {
    const {
      index
    } = e.target.dataset;
    this.setData({
      tableIndex: index,
    });
  },
  handleTab(e) {
    const {
      index
    } = e.target.dataset;
    this.setData({
      currentBtn: index,
    });
    if (index === 1) {
      this.getShopInfo();
    }
    if (index === 2) {
      this.setTime('today');
      this.setData({
        tabFkIndex: 0,
      });
      this.getVisitor();
    }
  },
  getVisitor() {
    let {
      currentIndex,
      startDate,
      endDate
    } = this.data;
    get(APIS.vip + '/vistor', {
        shop: currentIndex,
        start: startDate,
        end: endDate
      })
      .then(res => {
        this.setData({
          vistorList: res.data
        })
      })
  },
  getShopInfo() {
    get(`${APIS.shop}/${this.data.currentIndex}`).then(res => {
      this.setData({
        shopInfo: res.data,
        currentImg: res.data.qrcode
      });
    })
  },
  handleChange(e) {
    const {
      index
    } = e.target.dataset;
    this.setData({
      tabIndex: index,
    });
  },
  handleFkChange(e) {
    const {
      index
    } = e.target.dataset;
    this.setData({
      tabFkIndex: index,
    });
    if (index === 0) {
      this.setTime('today');
    } else if (index === 1) {
      this.setTime('yestoday');
    }
    this.getVisitor();
  },
  handleAdd() {
    let feeForm = this.data.feeForm;
    feeForm.push(['00:00', '24:00']);
    this.setData({
      feeForm
    })
  },
  handleDel(e) {
    let {
      idx
    } = e.currentTarget.dataset;
    let {
      feeForm
    } = this.data;
    feeForm.splice(idx, 1);
    this.setData({
      feeForm
    })
  },
  handleTable(e) {
    let {
      id,
      type
    } = e.currentTarget.dataset;
    let name = type === 'ball' ? 'selectBall' : 'selectCard';
    let select = this.data[name];
    let idx = select.findIndex(v => v === id);
    if (idx >= 0) {
      select.splice(idx, 1);
    } else {
      select.push(id)
    }
    this.setData({
      [name]: select
    })
  },
  handleUseFee() {
    let {
      rsid,
      selectBall,
      selectCard
    } = this.data;
    if (!selectCard.length && !selectBall.length) {
      wx.showToast({
        title: '请至少选择一个桌子',
        icon: 'none'
      })
      return;
    }
    put(APIS.rulesegment, {
      rsid,
      balls: selectBall,
      cards: selectCard
    }).then(res => {
      if (res.code === 0) {
        wx.showToast({
          title: '设置成功',
          icon: 'none'
        })
        this.setData({
          showPop: false
        })
      }
    })
  },
  bindStartChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let date = e.detail.value;
    let endDate = new Date(date) < new Date(this.data.endDate) ?
      this.data.endDate :
      date
    this.setData({
      startDate: date,
      endDate,
      tabFkIndex: -1
    }, () => {
      this.getVisitor();
    });
  },
  bindEndChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      endDate: e.detail.value,
      tabFkIndex: -1
    }, () => {
      this.getVisitor();
    })
  },
})